package com.mfnote.view.write;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import com.mfnote.adapter.WriteAdapter;
import com.mfnote.db.dao.HandDao;
import com.mfnote.db.dao.WriteDao;
import com.mfnote.util.FinalData;
import com.mfnote.util.ShareUtil;
import com.mfnote.util.image.ImageManager;
import com.mfnote.view.R;
import com.mfnote.view.R.anim;
import com.mfnote.view.R.id;
import com.mfnote.view.R.layout;
import com.mfnote.view.main.MainActivity;
import com.mfnote.view.other.MyApplication;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
/**
 * 记事本列表界面
 * @author ZHF
 *
 */
public class WriteActivity extends Activity {
	
	
	ListView write_lv = null;
	LinearLayout write_buttom_ll = null;
	//查询框
	RelativeLayout write_query_rl = null; 
	EditText mEditquery = null;
	Button mBtnQuery = null;
	private AutoCompleteTextView mMAutoCTextView;  //支持单个关键字自动查询，一个继承自EditView的可编辑的文本视图，能够实现动态匹配输入的内容
	
	//底部按钮
	Button btn_querylike,btn_batchdelete;
	
	public static String strbtnLock = ""; //删除框按钮的名字： 加锁 解锁
	
	ArrayList<HashMap<String, Object>> data = null; //ListView中的数据
//	SimpleAdapter adapter = null;
	
	HashMap<String, Object> map  = null; //长按事件对应项的值
	
	public static final int WRITE_NEWORDEATIL = 1;
	public static final int WRITE_BATCHDELETE = 2;

	private AlertDialog alertDlgIsDel; //长按记录弹出删除提示框
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.write);
		
		MyApplication.getInstance().addActivity(this);
		
		//新建记事
		Button btnAdd = (Button) this.findViewById(R.id.write_titlebar_btn_add);
		btnAdd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(WriteActivity.this, NewWriteActivity.class);
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.push_right_in,
						R.anim.push_left_out);
			}
		});
		write_lv = (ListView) findViewById(R.id.write_lv);
		//加载或更新listView中数据
		loadListView();
		
	}

	/**加载listView的数据**/
	private void loadListView() {
		
		//从数据库获取数据
	     data = new WriteDao(WriteActivity.this).getWriteAllCount();
		
//		 adapter = new SimpleAdapter(this, data, R.layout.write_listview_item,
//				new String[]{"title","time"}, new int[]{R.id.write_lv_title,R.id.write_lv_time});

		 write_lv.setAdapter(new WriteAdapter(WriteActivity.this, data));
		//添加点击监听器
		write_lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				HashMap<String, Object> map = (HashMap<String, Object>) parent.getItemAtPosition(position);
				
				Intent intent = new Intent(WriteActivity.this,NewWriteActivity.class);
				if(map.get("title").toString().equals("点我开始记事")) {
					startActivity(intent);
					finish();
					overridePendingTransition(R.anim.push_right_in,
							R.anim.push_left_out);
				}else {
					intent.putExtra("map",map);
					//requestCode为1---》代表请求跳转到NewWriteActivity界面
					startActivityForResult(intent,WRITE_NEWORDEATIL);
					finish();
					overridePendingTransition(R.anim.push_right_in,
							R.anim.push_left_out);
				}
			}
		});
		//添加长按事件
		write_lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				//此处弹出对话框提示是否删除此记录
			    map = (HashMap<String, Object>) parent.getItemAtPosition(position);
			    
			    if(Integer.parseInt(map.get("lock").toString()) == 1) {
			    	 strbtnLock = "解锁";
			    } else {
			    	  strbtnLock = "加锁";
			    }
				
				if(!map.get("title").equals("点我开始记事")) {  //第一条记录不能被删掉哦，谨记
						//打开删除对话框
						//loadDialog(map);
					//弹出多条选择框
					openDialog(map);
				}
				return false;
			}
		});
}

	/**提示删除对话框**/
	private void loadDialog(final HashMap<String, Object> map) {
		//对传入的item的map进行剖析处理
		LayoutInflater inflater=LayoutInflater.from(this);
		View viewDialog=inflater.inflate(R.layout.dialog_isdelete, null);
		alertDlgIsDel= new AlertDialog.Builder(this).create();
		alertDlgIsDel.show();
		Display display=this.getWindowManager().getDefaultDisplay();
		int width=display.getWidth();
		int height=display.getHeight();
		LayoutParams layoutParams=new LayoutParams(width*90/100,LayoutParams.WRAP_CONTENT);	
		alertDlgIsDel.setContentView(viewDialog, layoutParams);
		Button btn_delete_sure=(Button) viewDialog.findViewById(R.id.btn_delete_sure);
		Button btn_delete_cancel=(Button) viewDialog.findViewById(R.id.btn_delete_cancel);
		btn_delete_sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//删除数据
				//调用数据库删除操作
				long state = new WriteDao(WriteActivity.this).deleteWrite(map);
				 //添加成功
				 if(state != -1) {
					 Toast.makeText(WriteActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
					 loadListView();//更新一下列表
				 } else {
					 Toast.makeText(WriteActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
				 }
				alertDlgIsDel.dismiss();
			}
		});
		btn_delete_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgIsDel.dismiss();
			}
		});
		
//		builder.setNeutralButton(strbtnLock, new DialogInterface.OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				//锁定该条记录应该加个标记到数据库这样就不能删除了
//				int isLock = Integer.parseInt(map.get("lock").toString());
//				//如果为0，则没有锁定，可以加锁；为1的话，已被锁定，可以解锁
//				if(isLock == 0) {
//					new WriteDao(WriteActivity.this).updateWrite(map.get("title").toString(), 1);
//					Toast.makeText(WriteActivity.this, "此条记录也已被加锁，不可删除！", Toast.LENGTH_SHORT).show();
//					loadListView();
//				}else {
//					new WriteDao(WriteActivity.this).updateWrite(map.get("title").toString(), 0);
//					Toast.makeText(WriteActivity.this, "此条记录也已被解锁，可以删除！", Toast.LENGTH_SHORT).show();
//					loadListView(); //重新存数据库获取数据加载刷新列表
//				}
//			}
//		});
		
	}

	/**长按弹出操作对话框**/
	private void openDialog(final HashMap<String, Object> map) {
		//增加项：标题--您要进行的操作
		//     编辑
		//     删除
		//     加锁/解锁
		//     分享
		
		//自定义Context,添加主题
		Context dialogContext = new ContextThemeWrapper(WriteActivity.this, android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
		String[] choiceItems= new String[4]; //Theme_DeviceDefault_Light_DarkActionBar
		choiceItems[0] = "编辑";  
		choiceItems[1] = "删除";
		choiceItems[2] = strbtnLock;   // 加锁/解锁
		choiceItems[3] = "分享";  
		ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1,choiceItems);
		//对话框建立在刚才定义好的上下文上
		AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle("您要进行的操作");
		builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:  //编辑
					Intent intent = new Intent(WriteActivity.this,NewWriteActivity.class);
					intent.putExtra("map",map);
					intent.putExtra("isEdit", true);
					//requestCode为1---》代表请求跳转到NewWriteActivity界面
					startActivityForResult(intent,WRITE_NEWORDEATIL);
					finish();
					overridePendingTransition(R.anim.push_right_in,
							R.anim.push_left_out);
					break;
				case 1:  //删除
					//锁定该条记录应该加个标记到数据库这样就不能删除了
					//重新从数据库获取东西
				    int lock = Integer.parseInt(map.get("lock").toString());  //存数据库里获取
					//如果为0，则没有锁定，可以删除；为1的话，已被锁定，就不可以删除了
					if(lock == 0) {
						loadDialog(map);
					}else {
						Toast.makeText(WriteActivity.this, "此条记录已锁定不能删除！", Toast.LENGTH_LONG).show();
					}
					 
						
					break;
				case 2:  //加锁/解锁
//					//锁定该条记录应该加个标记到数据库这样就不能删除了
					int isLock = Integer.parseInt(map.get("lock").toString());
					//如果为0，则没有锁定，可以加锁；为1的话，已被锁定，可以解锁
					if(isLock == 0) {
						new WriteDao(WriteActivity.this).updateWrite(map.get("title").toString(), 1);
						Toast.makeText(WriteActivity.this, "此条记录也已被加锁，不可删除！", Toast.LENGTH_SHORT).show();
						loadListView();
					}else {
						new WriteDao(WriteActivity.this).updateWrite(map.get("title").toString(), 0);
						Toast.makeText(WriteActivity.this, "此条记录也已被解锁，可以删除！", Toast.LENGTH_SHORT).show();
						loadListView(); //重新存数据库获取数据加载刷新列表
					}
					break;
				case 3:  // 分享
					
					String saveimgPath = (String) map.get("imagePath");
					String strContent = (String) map.get("content");
					
					boolean temp  =new ImageManager(WriteActivity.this).subImagePathString(saveimgPath);
					if(temp == true) {  //里面只有一张图片
						ShareUtil.share(saveimgPath, strContent, WriteActivity.this);
					} else {
						if(saveimgPath.equals("")) { //没有图片，就只分享文字
							ShareUtil.share("", strContent, WriteActivity.this);
						}else {
							Toast.makeText(WriteActivity.this, "目前只能分享含有一张图片", Toast.LENGTH_SHORT).show();
						}
					}
					break;
				}
				dialog.dismiss();
			}
		});
		builder.create().show();
		
	}
	
	/**按键处理**/
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_MENU) {  //捕获Menu按键
			if(write_buttom_ll == null) {
				loadButtomMenu();
				onSearchRequested();
			}
			if(write_buttom_ll.getVisibility() == View.GONE) {
				write_buttom_ll.setVisibility(View.VISIBLE);
			} else {
				write_buttom_ll.setVisibility(View.GONE);;
			}
		}
		if(keyCode == KeyEvent.KEYCODE_BACK) { //捕获Back按键
			
			Intent intent = new Intent(WriteActivity.this,MainActivity.class);
			startActivity(intent);
			WriteActivity.this.finish();
			overridePendingTransition(R.anim.alpha_in,R.anim.scale_suoxiao_out
					);
		}
		return false;
	}
	
	/**加载底部菜单**/
	private void loadButtomMenu() {
		write_buttom_ll = (LinearLayout) findViewById(R.id.write_buttom_ll);

		//底部两菜单
		btn_querylike = (Button) findViewById(R.id.write_btn_querylike);
		btn_batchdelete = (Button) findViewById(R.id.write_btn_batchdelete);
		//查找
		btn_querylike.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Toast.makeText(WriteActivity.this, "接下来要干的就是弹出搜索框，进行模糊查询", 1).show();
				if(write_query_rl == null) {
					loadQuery();
					write_buttom_ll.setVisibility(View.GONE);
				}
				if(write_query_rl.getVisibility() == View.GONE) {
					write_query_rl.setVisibility(View.VISIBLE);
				} else {
					write_query_rl.setVisibility(View.GONE);;
				}
			}
		});
		//批量删除
		btn_batchdelete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				Toast.makeText(WriteActivity.this, "接下来要进行选择进行批量删除", 1).show();
				
				//跳转之前，先进行判断一下是否有数据（除了第一条）
				if(data.size()>1) {
					Intent intent = new Intent(WriteActivity.this,WriteBatchDeleteActivity.class);
					intent.putExtra("allwrites", data);
					startActivityForResult(intent, WRITE_BATCHDELETE); //接收批量删除后返回回来的数据
					finish();
					overridePendingTransition(R.anim.push_right_in,
							R.anim.push_left_out);
				} else {
					Toast.makeText(WriteActivity.this, "现在没有可以删除的记录！", Toast.LENGTH_LONG).show();
				}
				write_buttom_ll.setVisibility(View.GONE);
			}
		});
	}
	
	/**加载查询框**/
	private void loadQuery() {
		
		//自动提示框
		mMAutoCTextView = (AutoCompleteTextView) this.findViewById(R.id.autoctextview);
		//查询框
		mBtnQuery = (Button) findViewById(R.id.write_btn_query);
		write_query_rl = (RelativeLayout) findViewById(R.id.write_query_rl);
		
		//数据填充
		//对Data数据进行提取title重新包装
		String str = "";
		ArrayList<String> list = new ArrayList<String>();
		Iterator<HashMap<String, Object>> iter = data.iterator();
		while(iter.hasNext()) {
			HashMap<String, Object> map = iter.next();
			str = (String) map.get("title");
			list.add(str);
			 Log.i("WriteActivity",str);
		}
		//将ArrayList<String>----》String[]
		 String[] tempTitle=new String[list.size()];
         list.toArray(tempTitle);
		
         
		//创建一个ArrayAdapter  
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(WriteActivity.this,  
                android.R.layout.simple_dropdown_item_1line,tempTitle);  
        
        mMAutoCTextView.setAdapter(adapter);
		 //设置AutoCompleteTextView输入1个字符就进行提示  
        mMAutoCTextView.setThreshold(1);  
        
		//点击查询按钮进行查询
		mBtnQuery.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//接收数据
				String queryName = mMAutoCTextView.getText().toString();
				if(!queryName.equals("")) {  //编辑框中有内容
					//进行查询操作
					ArrayList<HashMap<String,Object>> list = new WriteDao(WriteActivity.this).queryByTitle(queryName);
//				Log.i("WriteActivity", list.toString());
					if(list != null) {  //能查询出来数据之后才能跳转
						//根据获取到的title直接跳转到其详情界面
						Intent intent = new Intent(WriteActivity.this,NewWriteActivity.class);
						intent.putExtra("writemap",list.get(0));//根据对方要接收的参数类型map,直接获取到list的第一条
						startActivity(intent);
						finish();
						overridePendingTransition(R.anim.push_right_in,
								R.anim.push_left_out);
						
						write_query_rl.setVisibility(View.GONE);
					}else {
						Toast.makeText(WriteActivity.this, "没有该项内容！", Toast.LENGTH_SHORT).show();
					}
				} 
				else{
					Toast.makeText(WriteActivity.this, "内容不能为空！", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
	
	/**再次回来时会调用的**/
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if(requestCode == WRITE_NEWORDEATIL) {  //从新建界面返回回来数据
			if(resultCode == 1) {
				//编辑成功，刷新列表,即重新加载列表数据
				loadListView();
				
			} else if(resultCode == 2) {
				//增加用户失败，不刷新主界面
			}
		}
		if(requestCode == WRITE_BATCHDELETE) {  
			if(resultCode == 1) {
				//删除成功，刷新列表,即重新加载列表数据
				loadListView();
				
			} else if(resultCode == 2) {
				//删除用户失败，不刷新主界面
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}
